<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../../lib/innerIframe-include-ext.js"></script>
<script type="text/javascript" src="../../lib/loader-theme.js"></script>
<script type="text/javascript" src="../../lib/ext/locale/ext-lang-zh_CN.js"></script>
<script type="text/javascript" src="../../lib/ext/plugins/DataTip.js"></script>
<script type="text/javascript" src="../../lib/commonUtil.js"></script>
<title>资源管理</title>
</head>
<script type="text/javascript">
Ext.Loader.setConfig({
    enabled: true
});
Ext.require([
    '*'
]);
var parentId = 0;
Ext.onReady(function () {
    Ext.QuickTips.init();
    Ext.define('resourceModel', {
        extend: 'Ext.data.Model',
        fields: [
            'res_id','res_name','parentname','res_key','res_url','res_type','res_sorder','res_desc','res_enable','icon'
        ],
        idProperty: 'res_id'
    });

    var store = Ext.create('Ext.data.Store', {
        id:'data_store',
        pageSize: 20,
        model: 'resourceModel',
        remoteSort: true,
        proxy: {
            type: 'ajax',
            url: '/resource/list',
            reader: {
                type: 'json',
                root: 'data',
                totalProperty: 'count'
            },
            simpleSortMode: true,
			listeners:{
                'exception':function( theproxy, response, operation, options ){
                    var data = eval("("+response.responseText+")");
                    if(!data.success){
                        Ext.Msg.alert('信息提示',data.msg);
                    } else {
                        Ext.Msg.alert("信息提示","网络错误，请稍候再试");
                    }
                }
            }
        },
        sorters: [
            {
                property: 'res_sorder',
                direction: 'ASC'
            }
        ]
    });
    
    var grid = Ext.create('Ext.grid.Panel', {
        store: store,
        loadMask: true,
        region: 'center',
        selModel: Ext.create('Ext.selection.CheckboxModel'),
        columns: [
            {
                text: "资源ID",
                dataIndex: 'res_id',
                hidden: true
            },
            {
                text:'图标',
                dataIndex:'icon',
                width:50,
                renderer: function(value, cellmeta, record, rowIndex, columnIndex, store) {
                    if(value)
                        return '<img width=16 height=16 src="' + value + '">';
                    else
                        return '';
                }
            },
            {
                text: '资源名称',
                dataIndex: 'res_name',
                width : 120

            },
            {
                text: '资源编码',
                dataIndex: 'res_key',
                width : 120

            },
            {
                text: '资源URL',
                dataIndex: 'res_url',
                width : 200

            },{
                text: '资源类型',
                dataIndex: 'res_type',
                width : 80,
                renderer:function(value){
                    if(value=="0"){
                        return "目录";
                    }else if(value=="1"){
                        return "菜单";
                    }else{
                    	return "按钮";
                    }
                }
            },{
            	text:'父级资源',
            	dataIndex:'parentname',
            	renderer:function(value){
            		if(!value)
            			return "根节点";
            		else
            			return value;
            	},
            	width:90
            },{
            	text:'显示顺序',
            	dataIndex:'res_sorder',
            	width:100
            },{
                text:'描述',
                dataIndex:'res_desc',
                width:200
            },{
            	text:'状态',
            	dataIndex:'res_enable',
            	width:100,
            	renderer:function(value){
            		if(value =='0' || value == '' || value == null){
            			return "<font color='green'>有效</font>";
            		} else {
            			return "<font color='red'>禁用</font>"
            		}
            	}
            }
        ],
        bbar: Ext.create('Ext.PagingToolbar', {
            store: store,
            displayInfo: true,
            displayMsg: '当前显示  {0} - {1} 共  {2} 条',
            emptyMsg: "没有数据显示！",
            beforePageText: "页码",
			afterPageText: "共 {0} 页",
			firstText:"首页",
			lastText:"末页",
			nextText:"下一页",
			prevText:"上一页",
			refreshText:"刷新"
        }),
        tbar: [
			{
			    icon : '../../img/add.png',
			    text: "添  加",
			    handler: function(){add_res()}
			},{
                text: "修  改",
                icon : '../../img/edit.png',
                handler: function(){upd_res()}
            },{
                icon : '../../img/delete.png',
                text: "删  除",
                handler: function(){del_res()}
            }

        ]
    });
	//创建资源树
	var tree = Ext.create('Ext.tree.Panel', {
        autoWidth:true,
        autoHeight:true,
        rootVisible: true,
        listeners:{
        	'itemclick':function(view, record, item, index, e, eOpts){
        		parentId = record.get('id');
        		store.loadPage(1,{params:{parentId:parentId}});
        	}
        }
    });
    //创建全景视图端
    var viewport = Ext.create('Ext.Viewport', {
        id: 'border-example',
        layout: 'border',//框式布局
        items: [

             {
                region: 'west',
                stateId: 'navigation-panel',
                id: 'west-panel',
                border:false,
                title: '资源树结构',
                split: true,
                width: 250,
                collapsible: true,
                margins: '0 0 0 5',
                layout: 'fit',
                items: tree
            },grid
           ]
    });

    var addWin;
    var addForm = new Ext.FormPanel({
    	url:'/resource/edit',
    	method:'POST',
    	frame:true,
    	bodyBorder:false,
    	bodyPadding:'20 20 0',
    	layout:'form',
        plugins: {
            ptype: 'datatip'
        },
    	fieldDefaults: {
    		msgTarget: 'side',
            labelWidth: 120
        },
    	items:[{
    		xtype:'hidden',
    		name:'res_id',
    		id:'resourceid',
    		value:''
    	},{
    		xtype:'hidden',
    		name:'parentId',
    		value:parentId,
    		id:'parentId'
    	},{
    		xtype:'textfield',
    		fieldLabel:'资源名称',
    		name:'res_name',
    		maxLength:50,
    		allowBlank:false,
    		tooltip:'请输入资源名称',
    		id:'res_name'
    	},{
    		xtype:'textfield',
    		fieldLabel:'资源唯一编码',
    		allowBlank:false,
    		maxLength:50,
    		name:'res_key',
    		id:'res_key',
       		validateOnChange:false, 
       		validator:function(){
       			var _value = this.getValue();
       			var _flag = true;
       			//仅添加时才验证
   				if(!Ext.isEmpty(_value) && Ext.isEmpty(Ext.getCmp('resourceid').getValue())){
   					Ext.Ajax.request({
   						async:false,
   	    	            url: '/resource/check?res_key='+_value,
   	    	            method : 'GET',
   	    	         	scope : this,// 如果通过 ajax 访问后台数据记得要加 async:false 同步
   	    	            success: function(response, opts) {
   	    	                var data = eval("("+response.responseText+")");
   	    	             	_flag = data.success;
   	    	            },
   	    	            failure: function(response, opts) {
   	    	            	var data = eval("("+response.responseText+")");
   	    	            	if(!data.success){
   	    	            		Ext.Msg.alert('信息提示',data.msg);
   	    	            	} else {
   	    	            		Ext.Msg.alert("信息提示","系统忙，请稍候再试");
   	    	            	}
   	    	            }
   	    	        });
   				}
   				if (_flag) {
   					return true;
   				} else {
   					this.markInvalid("此资源编码已存在！");
   					return false;
   				}
       		}
    	},{
    		xtype:'textfield',
    		fieldLabel:'资源URL',
    		allowBlank:true,
    		maxLength:200,
    		name:'res_url',
    		id:'res_url'
    	},{
            xtype: 'radiogroup',
            fieldLabel: '资源类型',
            vertical: true,
            id:'radio_type',
            items: [
				{
				    boxLabel: '目录',
				    name: 'res_type',
				    id:'catalog',
				    inputValue: '0'
				}, {
					checked:true,
				    boxLabel: '菜单',
				    name: 'res_type',
				    id:'menu',
				    inputValue: '1'
				}, {
				    boxLabel: '按钮',
				    id:'but',
				    name: 'res_type',
				    inputValue: '2'
				}
            ]
        },{
            xtype: 'radiogroup',
            fieldLabel: '资源状态',
            vertical: true,
            id:'radio_enable',
            //layout: 'anchor',
            items: [
				{
					checked:true,
				    boxLabel: '有效',
				    name: 'res_enable',
				    id:'enable0',
				    inputValue: '0'
				}, {
				    boxLabel: '禁用',
				    name: 'res_enable',
				    id:'enable1',
				    inputValue: '1'
				}
            ]
        },{
        	xtype:'textarea',
        	fieldLabel:'资源描述',
        	allowBlank:true,
        	name:'res_desc',
        	id:'res_desc',
        	maxLength:200 
        },{
        	xtype:'combo',
        	fieldLabel:'显示顺序',
        	allowBlank:true,
        	name:'res_sorder',
        	id:'sorder',
        	regex : /^[0-9]*$/,
            regexText:'只能是数字',
            store: Ext.create('Ext.data.Store', {
                fields: ['num', 'num'],
                data : []
            }),
            queryMode: 'local',
            width:80,
            displayField: 'num',
            valueField: 'num'
        },{
            xtype:'textfield',
            name:'icon',
            fieldLabel:'资源图标',
            maxLength:500
        }],
    	buttons:[{ 
    		text:'保  存',
    		icon:'../../img/accept.png',
    		handler:function(){
    			if(!addForm.getForm().isValid()){
    				 Ext.Msg.alert('信息提示','请检查输入项是否按要求填写！');
    				 return;
                }
    			if(Ext.getCmp('res_name').getValue().replace(/\s+/g,"") == ''){
       				Ext.Msg.alert('信息提示','资源名称不能为空！');
      				return;
       			}
    			if(Ext.getCmp('res_key').getValue().replace(/\s+/g,"") == ''){
       				Ext.Msg.alert('信息提示','资源编码不能为空！');
      				return;
       			}
            	var formValues = addForm.form.getValues();
                addForm.form.submit({
                	waitMsg:'正在保存数据...',
                	success:function(form,action){
                		if(action.result.success){
                			Ext.Msg.alert('信息提示',action.result.msg);
	                		store.reload();
	                		//还需要刷新资源树
	                		refreshResTree('/resource/tree', tree);
	                		addForm.form.reset();
	            			addWin.hide();
                		} else {
                			Ext.Msg.alert('信息提示',action.result.msg);
                		}
                	},
                	failure:function(form,action){
                		if(!action.result.success){
                			Ext.Msg.alert('信息提示',action.result.msg);
                		} else {
                			Ext.Msg.alert('信息提示','操作失败，请重试！');
                		}
                	}
                });
    		}
    	},{
    		text:'关  闭',
    		icon:'../../img/close.png',
    		handler:function(){
    			this.up('form').getForm().reset();
    			addWin.hide();
    		}
    	}]
    });
    function add_res(){
    	if(!addWin){
    		addWin = Ext.create('Ext.Window', {
        		title: '添加资源',
        		width: 500,
        		height: 400,
        		bodyPadding: '0 0 0',
        		'z-index': 9999999,
        		constrainHeader: true,
        		closeAction:'hide',
        		layout: 'fit',
        		items: addForm
        	});
    	}
    	//alert(parent_id);
    	Ext.getCmp('parentId').setValue(parentId);
    	//设置显示顺序
    	loadSort('add', addForm, store);
    	Ext.getCmp('sorder').setValue(store.getTotalCount()+1);
    	addWin.show();
    }
    function upd_res(){
    	var records = grid.getSelectionModel().getSelection();
    	if(records.length > 1){
			Ext.Msg.alert("信息提示","只能选择一条数据进行修改！");
			return;
		} 
    	if(records.length == 0){
    		Ext.Msg.alert("信息提示","请选择需要修改的数据！");
			return;
    	}
    	if(!addWin){
	    	addWin = Ext.create('Ext.Window', {
	    		title: '添加资源',
	    		width: 500,
	    		height: 400,
	    		bodyPadding: '0 0 0',
	    		'z-index': 9999999,
	    		constrainHeader: true,
	    		closeAction:'hide',
	    		layout: 'fit',
	    		items: addForm
	    	});
    	}
    	addForm.form.loadRecord(records[0]);
    	//设置当前操作数据的父Id
    	Ext.getCmp('parentId').setValue(parentId);
    	/**这里要注意，loadRecord无法自动给radio组选中，需要手动获取group下面的radio组件设置其setValue(true)**/
    	var radio_restype,radio_resenable;
    	if(records[0].get("res_type") == 0)
    		radio_restype = Ext.getCmp("radio_type").getComponent('catalog');
    	if(records[0].get("res_type") == 1)
    		radio_restype = Ext.getCmp("radio_type").getComponent('menu');
    	if(records[0].get("res_type") == 2)
    		radio_restype = Ext.getCmp("radio_type").getComponent('but');
    	radio_restype.setValue(true);
    	if(records[0].get('res_enable') == 0 || records[0].get('res_enable') == '' || records[0].get('res_enable') == null)
    		radio_resenable = Ext.getCmp("radio_enable").getComponent('enable0');
    	if(records[0].get('res_enable') == 1)
    		radio_resenable = Ext.getCmp("radio_enable").getComponent('enable1');
    	radio_resenable.setValue(true);
    	//设置显示顺序
    	loadSort('upd', addForm, store);
    	Ext.getCmp('sorder').setValue(records[0].get('res_sorder'));
    	addWin.show();
    }
    
    function del_res(){
    	var records = grid.getSelectionModel().getSelection();
    	if(records.length == 0){
    		Ext.Msg.alert("信息提示","请选择需要删除的数据！");
			return;
    	}
        if(records.length > 1){
            Ext.Msg.alert("信息提示","每次仅允许删除一条数据！");
            return;
        }
    	Ext.MessageBox.confirm('信息提示','确认删除吗？',function(val){
    		if(val == 'yes'){
    	    	Ext.Ajax.request({
    	            url: '/resource/del/'+records[0].get('res_id'),
    	            method : 'POST',
    	            success: function(response, opts) {
    	                var data = eval("("+response.responseText+")");
                        if(data.success){
                            Ext.Msg.alert('信息提示',data.msg,function(){
                                store.reload();
                                refreshResTree('/resource/tree', tree);
                            });
                        } else {
                            Ext.Msg.alert('信息提示',data.msg);
                        }
    	            },
    	            failure: function(response, opts) {
    	            	var data = eval("("+response.responseText+")");
    	            	if(!data.success){
    	            		Ext.Msg.alert('信息提示',data.msg);
    	            	} else {
    	            		Ext.Msg.alert("信息提示","网络错误，请稍候再试");
    	            	}
    	            }
    	        });
    		}
    	});
    }

    function queryStoreByCatId() {
    	var proxy = store.getProxy();
    	proxy.extraParams = {
    		parentId:parentId	
    	};
    	store.loadPage(1);
    }
	//初始化表格数据
	queryStoreByCatId();
	//初始化资源树root信息
	refreshResTree('/resource/tree', tree); 
    
});
</script>
<body>

</body>
</html>